package com.common.util.sftp.pool.client;

import com.common.util.sftp.SftpUtil;
import com.common.util.sftp.pool.SftpPool;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

/**
 * @author
 * @Describe 1个sftpClient
 * @date
 */
@NoArgsConstructor
@AllArgsConstructor
public class SftpClient implements ISftpClient {

    private SftpPool sftpPool;

    /**
     * 从sftp连接池获取连接并执行操作
     *
     * @param handler sftp操作
     */
    @Override
    public void open(Handler handler) {
        SftpUtil sftp = null;
        try {
            sftp = sftpPool.borrowObject();
            ISftpClient.Handler policyHandler = new DelegateHandler(handler);
            policyHandler.doHandle(sftp);
        } catch (Exception e) {
            throw new RuntimeException("获取sftp连接出错！", e);
        } finally {
            if (sftp != null) {
                sftpPool.returnObject(sftp);
            }
        }
    }

    @AllArgsConstructor
    static class DelegateHandler implements ISftpClient.Handler {

        private ISftpClient.Handler target;

        @Override
        public void doHandle(SftpUtil sftp) throws Exception {
            try {
                target.doHandle(sftp);
            } catch (Exception e) {
                // 捕获sftp操作的所有异常，包装成SftpClientException
                throw new RuntimeException("执行sftp操作出错！", e);
            }
        }
    }
}
